package com.tangcco.lockwell.controller.student;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.tangcco.lockwell.anno.AiPostExecute;
import com.tangcco.lockwell.base.RestResponse;
import com.tangcco.lockwell.config.RestTemplateConfig;
import com.tangcco.lockwell.domain.ExamPaper;
import com.tangcco.lockwell.domain.User;
import com.tangcco.lockwell.domain.dto.ai.AiDto;
import com.tangcco.lockwell.service.ExamPaperService;
import com.tangcco.lockwell.viewmodel.admin.exam.ExamPaperEditRequestVM;
import com.tangcco.lockwell.viewmodel.admin.exam.ExampaperAddAIVM;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import com.tangcco.lockwell.service.WrongQuestionService;
import com.tangcco.lockwell.domain.WrongQuestion;
import com.tangcco.lockwell.service.QuestionService;
import com.tangcco.lockwell.viewmodel.admin.question.QuestionVm;
import com.tangcco.lockwell.context.WebContext;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * AI分析相关的控制层
 */
@RestController
@RequestMapping("/api/student/ai")
@Slf4j
public class AiController {

    @Resource
    private RestTemplate aiClient;

    @Resource
    private WrongQuestionService wrongQuestionService;

    @Resource
    private QuestionService questionService;

    @Resource
    private WebContext webContext;

    @Resource
    private ExamPaperService examPaperService;

    /**
     * 转发到ai接口
     */
    @PostMapping("/forward/**")
    public RestResponse<JsonNode> forward(HttpServletRequest request, @RequestBody String requestBody) {
        try {
            // 获取请求路径
            String path = request.getRequestURI().substring(request.getContextPath().length());
            // 移除API前缀，得到实际需要转发的路径
            path = path.replaceFirst("/api/student/ai/forward", "");
            log.info("AI分析请求:{} , 请求参数:{}" ,path , requestBody);
            JsonNode response = aiClient.postForObject(RestTemplateConfig.aiUrl + path, requestBody, JsonNode.class);
            return RestResponse.ok(response);
        } catch (Exception e) {
            log.error("AI分析请求失败: ", e);
            return RestResponse.fail(500, "AI分析请求失败: " + e.getMessage());
        }
    }

    /**
     * 通用分析请求
     * 根据路径动态转发到对应的AI服务端点
     */
    @PostMapping("/**")
    @AiPostExecute
    public RestResponse<JsonNode> analyzeContent(HttpServletRequest request, @RequestBody AiDto aiDto) {
        try {
            // 获取请求路径
            String path = request.getRequestURI().substring(request.getContextPath().length());
            // 移除API前缀，得到实际需要转发的路径
            path = path.replaceFirst("/api/student/ai", "");
            log.info("AI分析请求:{} , 请求参数:{}" ,path ,aiDto.getText());
            JsonNode response = aiClient.postForObject(RestTemplateConfig.aiUrl + path, aiDto.getText(), JsonNode.class);
            return RestResponse.ok(response);
        } catch (Exception e) {
            log.error("AI分析请求失败: ", e);
            return RestResponse.fail(500, "AI分析请求失败: " + e.getMessage());
        }
    }


    /**
     * 政治智能练习接口
     * 获取最新错题并生成相似题目
     */
    @PostMapping("/politics/practice")
    public RestResponse<ExamPaper> politicsPractice(HttpServletRequest request) {
        try {
            // 1. 获取用户最新的错题
            List<WrongQuestion> wrongQuestions = wrongQuestionService.selectWrongQuestionsByUserId(
                webContext.getCurrentUser().getUserId(), null
            );
            
            if (CollectionUtils.isEmpty(wrongQuestions)) {
                return RestResponse.fail(400, "没有找到错题记录");
            }
            
            // 获取最新的一道错题
            WrongQuestion latestWrong = wrongQuestions.get(0);
            QuestionVm question = questionService.selectByIds(latestWrong.getQuestionId());
            
            if (question == null) {
                return RestResponse.fail(400, "未找到对应的题目信息");
            }

            // 2. 调用AI接口生成相似题目
            JsonNode aiResponse = aiClient.postForObject(
                RestTemplateConfig.aiUrl + "/politics/similar_questions",
                ImmutableMap.of("question", question.getTextContent()),
                JsonNode.class
            );

            // 3. 调用保存试卷接口
            ExampaperAddAIVM exampaperAddAIVM = new ObjectMapper().readValue(aiResponse.toString(), ExampaperAddAIVM.class);
            ExamPaperEditRequestVM model2 = examPaperService.ExamPaperAddAi(exampaperAddAIVM);
            User user = new User();
            user.setUserId(0);
            ExamPaper examPaper = examPaperService.savePaperFromVM(model2, user);

            return RestResponse.ok(examPaper);
        } catch (Exception e) {
            log.error("政治智能练习请求失败: ", e);
            return RestResponse.fail(500, "政治智能练习请求失败: " + e.getMessage());
        }
    }
} 